package sort;

public class Test_2 {
    public static void main(String[] args) {
        int []arr={2,56,24,785,12,85,23,3456,123,856,12,84,4235,23,735,58636,3124,523,735,124,8956};
       B.mergesort(arr,0,arr.length-1);
        for(int data:arr){
            System.out.print(data+" ");
        }
    }
}

class B{
    public static void mergesort(int[] arr,int left,int right){
        if(left==right){
            return;
        }
        //分治
        int mid=(left+right)/2;
        mergesort(arr,left,mid);
        mergesort(arr,mid+1,right);
        //合并
        merge(arr,left,right,mid);
    }

    public static void merge(int[] arr,int left,int right,int mid){
        int s1=left;
        int e1=mid;
        int s2=mid+1;
        int e2=right;
        //临时数组
        int k=0;
        int temarr[]=new int [right-left+1];
        while(s1<=e1&&s2<=e2){//取等？？
            if(arr[s1]<=arr[s2]){
                temarr[k++]=arr[s1++];
            }
            else{
                temarr[k++]=arr[s2++];
            }
        }

        while(s1<=e1){
            temarr[k++]=arr[s1++];
        }
        while(s2<=e2){
            temarr[k++]=arr[s2++];
        }
        //
        for(int i=0;i<temarr.length;i++){
            arr[i+left]=temarr[i];
        }
    }
}